<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var slidingPuzzle = function (board) {
      let m = 2, n = 3
      let sb = ''
      for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
          sb += board[i][j]
        }
      }
      let target = '123450'
      let step = 0
      let p = []
      let visited = new Set()
      visited.add(sb)
      p.push(sb)
      let neighbor = [[1, 3], [0, 4, 2], [1, 5], [0, 4], [3, 1, 5], [4, 2]]

      while (p.length) {
        let sz = p.length
        for (let i = 0; i < sz; i++) {
          let cur = p.shift()
          if (cur === target) {
            return step
          }
          let index = cur.indexOf('0')
          for (let j = 0; j < neighbor[index].length; j++) {
            let newStr = swap(cur, index, neighbor[index][j])
            if (!visited.has(newStr)) {
              visited.add(newStr)
              p.push(newStr)
            }
          }          
        }

        step++

      }
      return -1
    };

    function swap(s, i, j) {
      let arr = s.split('')
      let temp = arr[i]
      arr[i] = arr[j]
      arr[j] = temp
      return arr.join('')
    }

    console.log(slidingPuzzle([[1, 2, 3], [4, 0, 5]]));
  </script>
</body>

</html>